package com.personnalManagerSystem.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.personnalManagerSystem.model.Permission;
import com.personnalManagerSystem.service.IPermissionService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author liqing
 * @Date: 2022/3/27 19:32
 * @Description
 */
@Configuration
public class ShiroConfig {
    @Autowired
    IPermissionService iPermissionService;
    //
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilter.setSecurityManager(securityManager());
        //设置未登录前往页面
        shiroFilter.setLoginUrl("/view/login");
        //设置权限权不够页面
        shiroFilter.setUnauthorizedUrl("/view/unauthorized");
        //设置过滤链
        Map<String, String> filterMap=new LinkedHashMap<>();
        filterMap.put("/view/login","anon");
        filterMap.put("/login/*","anon");
//        filterMap.put("/css/*","anon");
//        filterMap.put("/fonts/*","anon");
//        filterMap.put("/img/*","anon");
//        filterMap.put("/js/*","anon");
        filterMap.put("/static/*","anon");
        //查看权限表
        List<Permission> list = iPermissionService.list();

        for (Permission sysPermission : list) {
            if (sysPermission.getPermissionUrl()!=null && !sysPermission.getPermissionUrl().equals("")){
                filterMap.put(sysPermission.getPermissionUrl(),"perms["+sysPermission.getPermissionCode()+"]");
            }
        }

        filterMap.put("/*","authc");
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        //返回shiroFilterFactoryBean对象
        return shiroFilter;
    }

    //创建安全管理器对象
    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm());
        return securityManager;
    }
    //自定义Realm,用以关联数据库
    @Bean
    public MyRealm myRealm(){
        MyRealm myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(credentialsMatcher());
        return myRealm;
    }
    //自定义加密的方式-----MD5加密
    @Bean
    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(1024);
        return matcher;
    }
    //springmvc整合shiro属性(否则报错)
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }




}
